package com.talkyun.utils.loader;

import com.talkyun.utils.HttpUtils;
import com.talkyun.utils.loader.impl.DiskStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static com.talkyun.utils.MD5.md5;

/**
 * @author kevin
 */
public class HttpWithCacheLoader {
    private Logger logger = LoggerFactory.getLogger(HttpWithCacheLoader.class);

    /**
     * @param retryNum 异常时重试次数
     */
    public String load(String url, String form, int timeout, int retryNum) {
        HttpUtils http = new HttpUtils(url, timeout);

        String file = "loader-" + md5(url + "$$" + form);
        DiskStore disk = new DiskStore(file);

        // First load from http
        for (int i = 0; i < retryNum; i++) {
            try {
                String text = isBlank(form) ? http.get() : http.post(form);
                disk.store(text);
                return text;
            } catch (IOException e) {
                this.sleep((i + 1) * 1000);
            }
        }

        logger.warn("Load {} from file ... {}", url, file);
        // Second: load from disk
        return disk.load();
    }

    private void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            // ignore
        }
    }

    private boolean isBlank(String s) {
        return s == null || s.trim().length() == 0;
    }
}